package com.eboss.sbs.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import com.dtr.zxing.activity.MyCaptureActivity;
import com.eboss.sbs.R;
import com.eboss.sbs.activity.base.BaseActivity;
import com.eboss.sbs.http.API;
import com.eboss.sbs.http.HttpCallback;
import com.eboss.sbs.model.CaculateMoneyEntity;
import com.eboss.sbs.model.MemberBenifitEntity;
import com.google.gson.reflect.TypeToken;
import com.mytools.tool.utils.StringUtil;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class PayMoneyInputActivity extends BaseActivity {
	
	public static final int REQUEST_SCAN_MEMBER_NO = 1;
	
	private String txt_show;
	
	private int paytype = 0;
	
//	CREATED：订单已创建/支付中。
//	PAID：订单支付成功。
//	PAY_CANCELED：支付失败并且已经成功充正。
//	PAY_ERROR：支付失败，不确定是否已经成功充正。 REFUNDED：已成功全额退款。
//	PARTIAL_REFUNDED：已成功部分退款。
//	REFUND_ERROR：退款失败并且不确定第三方支付通道的最终退款状态。 CANCELED：客户端发起的撤单已成功。
//	CANCEL_ERROR：客户端发起的撤单失败并且不确定第三方支付通道的最终状态
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		mActivity = this;
		setContentView(R.layout.activity_pay_money_input);
		super.onCreate(savedInstanceState);
		
		setTvText(R.id.tv_title, "输入收款金额");
		
		setTvText(R.id.key_caculate, "去\n\n收\n\n款");
		initView();
		
		IntentFilter filter = new IntentFilter(RECEIVER_CLEAN_DATA_TAG); 
        registerReceiver(broadcastReceiver, filter);
        
	}
	
	private void initView(){
		
		findViewById(R.id.titleback_btn_back).setOnClickListener(this);
		findViewById(R.id.key_1).setOnClickListener(this);
		findViewById(R.id.key_2).setOnClickListener(this);
		findViewById(R.id.key_3).setOnClickListener(this);
		findViewById(R.id.key_4).setOnClickListener(this);
		findViewById(R.id.key_5).setOnClickListener(this);
		findViewById(R.id.key_6).setOnClickListener(this);
		findViewById(R.id.key_7).setOnClickListener(this);
		findViewById(R.id.key_8).setOnClickListener(this);
		findViewById(R.id.key_9).setOnClickListener(this);
		findViewById(R.id.key_dot).setOnClickListener(this);
		findViewById(R.id.key_0).setOnClickListener(this);
		findViewById(R.id.key_00).setOnClickListener(this);
		findViewById(R.id.key_del).setOnClickListener(this);
		findViewById(R.id.key_caculate).setOnClickListener(this);
		
		findViewById(R.id.btn_scan_no).setOnClickListener(this);
		
		TextView tv = (TextView) findViewById(R.id.tv_show);
		tv.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				boolean isnum = (!StringUtil.isNull(txt_show))&&isNumber(txt_show)&&(!txt_show.equals(0));
				setTvEnable(R.id.key_caculate, isnum);
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override
			public void afterTextChanged(Editable s) {}
		});

	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.key_1: key_event("1"); break;
			case R.id.key_2: key_event("2"); break;
			case R.id.key_3: key_event("3"); break;
			case R.id.key_4: key_event("4"); break;
			case R.id.key_5: key_event("5"); break;
			case R.id.key_6: key_event("6"); break;
			case R.id.key_7: key_event("7"); break;
			case R.id.key_8: key_event("8"); break;
			case R.id.key_9: key_event("9"); break;
			case R.id.key_dot: key_event("."); break;
			case R.id.key_0: key_event("0"); break;
			case R.id.key_00: key_event("00"); break;
			case R.id.key_del:del_event(); break;
			case R.id.key_caculate: getMemberInfo(); break;
			case R.id.titleback_btn_back: finish(); break;
			case R.id.btn_scan_no: scan(); break;
			default:break;
		}
	}
	
	private void scan(){
		Intent openCameraIntent = new Intent(mActivity, MyCaptureActivity.class);
        startActivityForResult(openCameraIntent, REQUEST_SCAN_MEMBER_NO); 
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode!=RESULT_OK)return;
		if(requestCode == REQUEST_SCAN_MEMBER_NO){
			String result = data.getStringExtra(MyCaptureActivity.SCAN_RESULT);
			if(!StringUtil.isNull(result)){setTvText(R.id.tv_scan_no, result);}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void key_event(String key){
		
		if(StringUtil.isNull(txt_show)){
			if(key.equals("."))return;
			if(key.equals("00"))return;
		}
		else{
			if(txt_show.contains(".")&&key.equals("."))return;
			else if(txt_show.equals("0")&&key.equals("0"))return;
			else  if(Pattern.compile(".*\\.\\d{2}").matcher(txt_show).matches()){return;}
			else {
				String txt_show_tmp = txt_show.replaceFirst("\\..*", "");
				if(!StringUtil.isNull(txt_show_tmp)&&txt_show_tmp.length()>8){return;}
			}
		}
		
		txt_show = (StringUtil.isNull(txt_show)?"":txt_show) + key;
		setTvText(R.id.tv_show, "￥"+txt_show);
		
	}
	
	private void del_event(){
		if(StringUtil.isNull(txt_show)){return;}
		else{
			int length = txt_show.length();
			txt_show = txt_show.substring(0, length-1);
			setTvText(R.id.tv_show, StringUtil.isNull(txt_show)?"":("￥"+txt_show));
		}
	}
	
	private boolean isNumber(String in){
		if(StringUtil.isNull(in))return false;
		boolean isZero = Pattern.compile("(0|\\.)+").matcher(in).matches();
		if(isZero)return false;
		try{
			Float.parseFloat(in);
			return true;
		}
		catch(Exception e){return false;}
	}
	
	private double getPayAmount(){
		if(StringUtil.isNull(txt_show))return 0;
		else {
			try{
//				double f_pay_amount = Double.parseDouble(txt_show);
//				double f_pay_amount_cent = f_pay_amount * 100;

				BigDecimal big = new BigDecimal(txt_show);
				double  f_pay_amount_cent = big.multiply(new BigDecimal(100)).doubleValue();
				return f_pay_amount_cent;
			}
			catch(Exception e){return 0;}
		}
	}
	
	private void getMemberInfo() {
		
		String member_phone = getTvText(R.id.tv_scan_no);
		if(StringUtil.isNull(member_phone)){
			CaculateMoneyEntity data3 = new CaculateMoneyEntity();
			data3.setTradeMoney((int)getPayAmount());
			data3.setRealMoney((int)getPayAmount());
			data3.setCouponCoverMoney(0);
			data3.setPointCoverMoney(0);
			data3.setCouponNum(0);
			Intent intent = new Intent(mActivity, PayChannelChooseActivity.class);
			intent.putExtra(PayChannelChooseActivity.CACULATE_MONEY_ENTITY, data3);
			intent.putExtra(PayChooseBenifitActivity.SQB_PAY_TYPE, paytype);
			startActivity(intent);
			return;
		}
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sid", mApp.getLoginEntity().getSid());
		String mobile = getTvText(R.id.tv_scan_no);
		params.put("tradeMoney",  (int)getPayAmount());
		
		if(!StringUtil.isNull(mobile)){params.put("mobile", mobile);}
		API.http_post(this, API.MEMBER_BENIFIT, params, new HttpCallback<MemberBenifitEntity>(this) {
			@Override
			public void onSuccess(int statusCode, MemberBenifitEntity data) {
				Intent intent = new Intent(mActivity, PayChooseBenifitActivity.class);
				intent.putExtra(PayChooseBenifitActivity.SQB_PAY_MONEY_INT, (int)getPayAmount());
				intent.putExtra(PayChooseBenifitActivity.SQB_PAY_TYPE, paytype);
				intent.putExtra(PayChooseBenifitActivity.MEMBER_BENIFIT, data);
				startActivity(intent);
			}

			@Override
			public void onFailure(int statusCode, String message) {
				super.onFailure(statusCode, message);
			}
			
			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override
			public TypeToken getTypeToken() {
				return new TypeToken<MemberBenifitEntity>() {
				};
			}
		});
	}
	
	public static String RECEIVER_CLEAN_DATA_TAG = "RECEIVER_CLEAN_DATA_TAG";
	public static String NOTIFY_CODE_TAG = "NOTIFY_CODE_TAG";
	public static int DEFAULT_DATA = 0;
	public static int CLEAN_DATA = 1;
	
	/**更新购物车物品数量标识*/
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			int notify_code = intent.getIntExtra(NOTIFY_CODE_TAG, DEFAULT_DATA);
			if(notify_code == CLEAN_DATA){
				cleanData();
			}
		}
	};
	
	private void cleanData(){
		txt_show = "";
		setTvText(R.id.tv_show, "");
		setTvText(R.id.tv_scan_no, "");
	}
	
	protected void onDestroy() {
		unregisterReceiver(broadcastReceiver);
		super.onDestroy();
	};
	
}
